package app.controllers;

import app.models.CH;
import app.services.CHService;
import app.services.ConvenioService;
import br.com.caelum.vraptor.Get;
import br.com.caelum.vraptor.Post;
import br.com.caelum.vraptor.Resource;
import br.com.caelum.vraptor.Result;
import br.com.caelum.vraptor.Validator;
import br.com.caelum.vraptor.validator.ValidationMessage;

@Resource
public class CHController extends Controller {

	private final Result result;
	private final CHService service;
	private final Validator validator;
	private final ConvenioService convenioService;
	
	public CHController(Result result,
			CHService service, Validator validator, ConvenioService convenioService) {

		this.result = result;
		this.service = service;
		this.validator = validator;
		this.convenioService = convenioService;
	}
	
	@Get("/cH")
	public void index() {
		this.result.include("chs", this.service.findAll());
	}
	
	@Get("/cH/new")
	public void form() {
		this.result.include("convenios",convenioService.findAll());
	}
	
	@Post("/cH/save")
	public void save(CH ch) {
		for(CH items: service.findAll()){
			if(items.getIdConvenio() == ch.getIdConvenio()){
				validator.add(new ValidationMessage("Já existe um CH cadastrado para este Convênio.", "erro"));
			}
		}
		
		validator.validate(ch);
		validator.onErrorRedirectTo(this).form();
		
		service.create(ch);
		
		this.result.redirectTo(this).index();
	}
	
	@Get("/cH/{id}/edit")
	public void edit(Long id) {
		this.result.include("convenios", convenioService.findAll());
		this.result.include("ch", service.find(id));
	}
	
	@Post("/cH/update")
	public void update(CH ch) {
		/*if(service.findAll().size() > 1){
			validator.add(new ValidationMessage("Já existe um CH cadastrado", "erro"));
		}*/
		validator.validate(ch);
		
		validator.onErrorRedirectTo(this).edit(ch.getId());
		service.update(ch);
		
		this.result.redirectTo(this).index();
	}
	
}
